<?php
require "rsa.php";
require "jwt.php";
require "util.php";

header('Access-Control-Allow-Origin:*');
header("Access-Control-Allow-Methods:*");
header("Access-Control-Allow-Headers:Content-Type,XFILENAME,XFILECATEGORY,XFILESIZE,Authorization");


$postMethod = @$_POST['request'];
$getMethod = @$_GET['request'];
$headers = getallheaders();
$jwt = @$headers['Authorization'];

$payload = array(
    'uid' => '001',
    'unm' => 'zzn',
    'prv' => 8,
    'llt' => '150000000',//上次登录
    'lot' => '160000000',//过期时间

);

//routers
$gets = array(
    'getPubKey' => 'getPubKey',
    'getList' => 'getList',
    'getAllInfo' => 'getAllInfo',
    'getArticle' => 'getArticle',


);

$posts = array(
    'login' => 'login',
    'register' => 'register',
    'changePrivilege' => 'changePrivilege',
    'delUser' => 'delUser',
    'changePawd' => 'changePawd',
    'publish' => 'publish',
    'delArticle' => 'delArticle',
    'addArticle' => 'addArticle',
    'updateArticle' => 'updateArticle',


);


if (!empty($getMethod)) {
    echo $gets[$getMethod]();
} elseif (!empty($postMethod)) {
    echo $posts[$postMethod]();
} else {
    echo 'server is runnning' . $postMethod . $getMethod;
}


function getPubKey()
{
    return_result(array('code' => 200, 'data' => array('key' => RSA::getPublic()), 'msg' => 'getkey'));
}

function login()
{
    $username = $_POST['username'];
    $epawd = $_POST['password'];
    $check = $_POST['checked'];

    $password = RSA::decryptByPrivate($epawd);

    $pdo = getConnection();
    $stm = $pdo->prepare("select uid,username,password,privilege from users where username = ?");
    $stm->bindParam(1, $username);
    $stm->execute();
    $result = $stm->fetchAll();
    if (count($result) > 0) {
        if ($result[0]['username'] == $username && $result[0]['password'] == $password) {
            $uid = $result[0]['uid'];
            $priv = $result[0]['privilege'];
            if ($check == 'true') {
                $payload = array('uid' => $uid, 'umn' => $username, 'llt' => time(), 'lov' => time() + 7 * 24 * 3600, 'pri' => $priv);
            } else {
                $payload = array('uid' => $uid, 'umn' => $username, 'llt' => time(), 'lov' => time() + 3600, 'pri' => $priv);
            }
            $token = JWT::getTocken($payload);
            updateToken($pdo, $uid, $token);
            return_result(array('code' => '200', 'data' => array('token' => $token), 'msg' => '登录成功！'));
        } else {
            return_result(array('code' => '400', 'data' => '', 'msg' => '密码错误!'));
        }
    } else {
        return_result(array('code' => '400', 'data' => '', 'msg' => '用户名不存在!'));
    }
}

function register()
{
    $username = $_POST['username'];
    $epawd = $_POST['password'];
    $check = $_POST['checked'];

    $password = RSA::decryptByPrivate($epawd);

    $pdo = getConnection();
    $stm = $pdo->prepare("select username,password from users where username = ?");
    $stm->bindParam(1, $username);
    $stm->execute();
    $result = $stm->fetchAll();
    if (count($result) == 0) {
        $stm = $pdo->prepare("insert into users (username,password,privilege) values (?,?,?)");
        $stm->bindParam(1, $username);
        $stm->bindParam(2, $password);
        $stm->bindValue(3, 0);
        $stm->execute();

        $stm = $pdo->prepare("select uid,username from users where username = ?");
        $stm->bindParam(1, $username);
        $stm->execute();
        $result = $stm->fetchAll();

        $uid = $result[0]['uid'];

        if ($check == 'true') {
            $payload = array('umn' => $username, 'uid' => $uid, 'llt' => time(), 'lov' => time() + 7 * 24 * 3600);
        } else {
            $payload = array('umn' => $username, 'uid' => $uid, 'llt' => time(), 'lov' => time() + 3600);
        }
        $token = JWT::getTocken($payload);
        updateToken($pdo, $uid, $token);
        return_result(array('code' => '200', 'data' => array('token' => $token), 'msg' => '登录成功!'));
    } else {
        return_result(
            array('code' => '400', 'data' => '', 'msg' => '用户名已存在!')
        );
    }
}

function getList()
{
    $count = @$_GET['count'];//14
    $offset = @$_GET['offset'];//1
    $type = @$_GET['type'];
    $pdo = getConnection();
    $stmt = $pdo->prepare("select count(*) from articles where part_type = $type and state = 0 ");
    $stmt->execute();
    $total = $stmt->fetchAll();

    $sql = 'select a_id,title,publish_time,state from articles where part_type = ' . $type . ' order by publish_time desc limit ' . $count * $offset . " , " . $count;
    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    $res = $stmt->fetchAll();
    return_result(array('code' => 200, 'data' => array('total' => $total, "list" => $res), 'msg' => 'success'));
}

function getAllInfo()
{
    $pdo = getConnection();
    $stm = $pdo->prepare("select uid,username,privilege from users");
    $stm->execute();
    $result = $stm->fetchAll();

    array_shift($result);

    for ($i = 0; $i < count($result); $i++) {
        $p = (int)$result[$i]['privilege'];


        if ($p - 4 >= 0) {
            $result[$i]['x'] = true;
            $p -= 4;
        } else {
            $result[$i]['x'] = false;
        }

        if ($p - 2 >= 0) {
            $result[$i]['w'] = true;
            $p -= 2;
        } else {
            $result[$i]['w'] = false;
        }

        if ($p - 1 >= 0) {
            $result[$i]['r'] = true;
            $p -= 1;
        } else {
            $result[$i]['r'] = false;
        }

    }
    return_result(array('code' => '200', 'data' => array('users' => $result), 'msg' => 'success'));
}

function changePrivilege()
{
    $id = @$_POST['id'];
    $priv = @$_POST['pri'];

    $pdo = getConnection();
    $stm = $pdo->prepare("update users set privilege = ? where uid = ?");
    $stm->bindValue(1, $priv);
    $stm->bindValue(2, $id);
    $stm->execute();
    return_result(array('code' => '200', 'data' => array($id, $priv), 'msg' => '修改权限成功'));

}

function delUser()
{
    $id = @$_POST['uid'];

    $pdo = getConnection();
    $stm = $pdo->prepare("delete from users where uid = ?");
    $stm->bindValue(1, $id);
    $stm->execute();
    return_result(array('code' => '200', 'data' => "", 'msg' => '删除用户成功'));

}

function changePawd()
{
    $id = @$_POST['uid'];
    $edpwd = @$_POST['password'];

    $pwd = RSA::decryptByPrivate($edpwd);

    $pdo = getConnection();
    $stm = $pdo->prepare("update users set password = ? where uid = ?");
    $stm->bindValue(1, $pwd);
    $stm->bindValue(2, $id);
    $stm->execute();
    return_result(array('code' => '200', 'data' => '', 'msg' => '密码修改成功'));

}

function publish()
{
    $ids = @$_POST['a_ids'];
    $state = @$_POST['state'];

    $ids = explode(',', $ids);

    $pdo = getConnection();
    for ($i = 0; $i < count($ids); $i++) {
        $stm = $pdo->prepare("update articles set state = ?,publish_time = ? where a_id = ?");
        $stm->bindValue(1, $state);
        $stm->bindValue(2, time());
        $stm->bindValue(3, $ids[$i]);
        $stm->execute();
    }

    return_result(array('code' => '200', 'data' => '', 'msg' => '状态修改成功'));

}

function delArticle()
{
    $ids = @$_POST['a_ids'];

    $ids = explode(',', $ids);

    $pdo = getConnection();
    for ($i = 0; $i < count($ids); $i++) {
        $stm = $pdo->prepare("delete from articles where a_id = ?");
        $stm->bindValue(1, $ids[$i]);
        $stm->execute();
    }

    return_result(array('code' => '200', 'data' => '', 'msg' => '删除成功'));

}

function addArticle()
{
    $title = urldecode(@$_POST['title']);
    $content = urldecode(@$_POST['content']);
    $author = urldecode(@$_POST['author']);
    $part = (int)@$_POST['part'];

    $content = "b'".base64_encode($content);

    $pdo = getConnection();
    $stm = $pdo->prepare("insert into articles (part_type,author,title,publish_time,content) values (?,?,?,?,?)");
    $stm->bindValue(1, $part);
    $stm->bindValue(2, $author);
    $stm->bindValue(3,$title);
    $stm->bindValue(4,time());
    $stm->bindValue(5,$content);
    $stm->execute();

    return_result(array('code' => '200', 'data' => '', 'msg' => '创建成功'));

}

function getArticle(){
    $id = @$_GET['id'];
    $pdo = getConnection();

    $sql = 'select * from articles where a_id = '.$id;
    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    $res = $stmt->fetchAll();
    $item = $res[0];
    $raw = $item['content'];
    $result = explode("'",$raw)[1];
    $item['content'] = base64_decode($result);
    return_result(array('code'=>200,'data'=>array("item"=>$item),'msg'=>'success'));
}

function updateArticle(){
    $title = urldecode(@$_POST['title']);
    $content = urldecode(@$_POST['content']);
    $author = urldecode(@$_POST['author']);
    $part = (int)@$_POST['part'];
    $id = @$_POST['id'];

    $content = "b'".base64_encode($content);

    $pdo = getConnection();
    $stm = $pdo->prepare("update articles set part_type=?,author=?,title=?,publish_time=?,content=? where a_id=?");
    $stm->bindValue(1, $part);
    $stm->bindValue(2, $author);
    $stm->bindValue(3,$title);
    $stm->bindValue(4,time());
    $stm->bindValue(5,$content);
    $stm->bindValue(6,$id);
    $stm->execute();

    return_result(array('code' => '200', 'data' => '', 'msg' => '创建成功'));
}